package com.passport_main.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.io.grpc.internal.JsonUtil;
import com.common.pojo.MyUserDetails;
import com.common.result.JsonResult;
import com.common.result.ResultEnum;
import com.common.utils.JwtUtils;
import com.passport_main.dao.mapper.PassportMapper;
import com.passport_main.pojo.dto.LoginDTO;
import com.passport_main.pojo.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PassportService {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Autowired
    PassportMapper passportMapper;

    @Value("${jwt.secretKey}")
    private String secretKey;

    public JsonResult login(LoginDTO loginDTO, HttpServletRequest httpServletRequest,String addr,String userAgent) {

        log.info("service：用户上传dto: {}", loginDTO);
        log.info("server:用户地址:{}",addr);

        // 1. 验证账号是否存在

        UserLoginVO userLoginVO = passportMapper.selectUserByAccount(loginDTO.getAccount());
        log.info("service:用户账号{}",userLoginVO);
        if (userLoginVO == null) {
            return new JsonResult(ResultEnum.USER_ACCOUNT_OR_PASSWORD_ERROR,"hahahha我是data");
//            log.info("service返回erorr:{}",new JsonResult(ResultEnum.USER_ACCOUNT_OR_PASSWORD_ERROR));
        }
        String nickname=userLoginVO.getNickname();
        String receiveInfo=userLoginVO.getReceiveInfo();


        // 2. 验证密码
        String password = userLoginVO.getPassword();
        log.info("service: 返回给前端的vo: {}", userLoginVO);

        if (!loginDTO.getPassword().equals(password)) {
            return new JsonResult(ResultEnum.USER_ACCOUNT_OR_PASSWORD_ERROR);
        }

        // 3. 验证账号状态
        long uid = userLoginVO.getUid();
        int isUsing = userLoginVO.getIsUsing();
        int isEnable = userLoginVO.getIsEnable();

        if (isUsing != 1) {
            return new JsonResult(ResultEnum.USER_ACCOUNT_OR_PASSWORD_ERROR);
        }

        if (isEnable != 1) {
            return new JsonResult(ResultEnum.USER_ACCOUNT_HAS_BEEN_ABANDON);
        }

        // 4. 生成JWT
        Map<String, Object> claim = new HashMap<>();
        claim.put("uid",uid);
        Collection<String> permission=new HashSet<String>();
//        查看用户主页
        permission.add("localhost://8082");
//        发布文章/
        permission.add("http:localhost:8083/v1/article/post");
        permission.add("http:localhost:8083/v1/article/post/editor");
        //下单
        permission.add("http:localhost:80");
        //查看自己发布的文章
        permission.add("http:localhost:8083/v1/article/getUserArticles");
        //获取首页文章
        permission.add("http:localhost:8083/v1/article/getIndexArticles");
        //根据aid查看特定某一篇文章
        permission.add("http:localhost:8083/v1/article/getArticle");


        MyUserDetails myUserDetails=new MyUserDetails();
        myUserDetails.setUid(uid);
        myUserDetails.setNickname(nickname);
        myUserDetails.setReceive_info(receiveInfo);



        claim.put("address",addr);
        claim.put("permission",permission);
        claim.put("userAgent",userAgent);
        long time=System.currentTimeMillis();
        claim.put("time", time);

        String s = JSON.toJSONString(myUserDetails);

        log.info("来来来看看这个java对象有没有转换成Json:{}",s);
        claim.put("userDetails",myUserDetails);


        String jwt = JwtUtils.generate(claim);

        // 5. 存储JWT到Redis



        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String redisKeyName="user"+uid+"jwt";

        try {
//            stringSerializableValueOperations.set(redisKeyName, (Serializable)claim);
            valueOperations.set(redisKeyName, jwt, 15, TimeUnit.MINUTES);
            log.info("service: 返回jwt: Bearer {}", jwt);
            return new JsonResult(ResultEnum.SECCESS, "Bearer "+jwt);

        }catch (Exception e){
            log.error("Redis存储JWT失败: ", e);
            return new JsonResult(ResultEnum.REDIS_STORAGE_JWT_ERROR);
        }
//        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
//        try {
//            opsForHash.put("jwt", jwtFieldName, "Bearer "+(Serializable)claim);
//            log.info("service: 返回jwt: Bearer {}", jwt);
//            return new JsonResult(ResultEnum.SECCESS, jwt);
//        } catch (Exception e) {
//
//        }
    }
}